import { observer } from 'mobx-react-lite';
import React, { useState, useRef, useEffect } from 'react';
import { Drawer, Form, Button, Dialog, Tag, Notification } from '@alifd/next';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { TitleGrid, FieldsGrid, ENUMS } from '../../stores/definitions';
import { useStore } from '@/hooks';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;

const Index = ({ visible, task, onCancel, modal, onSubmit }) => {
  const { rsTaskStore: store } = useStore();
  const [alteration] = useState(() => observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  const [companys, setCompanys] = useState([]);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (JSON.stringify(task) !== '{}') {
      const data = task;
      _.assign(alteration, data);
      editCtx.origin = _.cloneDeep(task);
      (async () => {
        const res = await store.company({ isOperating: false });
        setCompanys(res);
      })();
    }
    return (() => {
      _.set(alteration, 'arCarrierCompanyId', '');
      _.set(alteration, 'arCarrierCompanyPrice', '');
      _.set(alteration, 'arCarrierCompanyName', '');
    });
  }, [task]);

  // 自定义标题
  const titleElement = (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <div style={{ marginRight: 10 }}>{t`任务【${task?.id}】变更`}</div>
      <Tag type="normal" color="blue">
        {ENUMS.states[task?.state]}
      </Tag>
    </div>
  );

  const overrideModel = {
    arCarrierCompanyId: {
      label: t`承运公司`,
      ui: {
        renderer: (v) => {
          return <TauSimpleSelect data={companys} value={v} onChange={handleArCompany} />;
        },
        itemProps: {
          required: true,
        },
      },
    },
  };

  const handleArCompany = (v, __, e) => {
    if (v) {
      const { label } = e;
      _.set(alteration, 'arCarrierCompanyName', label);
    } else {
      _.set('arCarrierCompanyName', '');
    }
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(alteration, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
    // console.log('form data: ', name, value, toJS(alteration));
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('...errors', errors);
      return;
    }
    if (currentSendCar(alteration)) return;
    if (priceCurrentExceed(alteration)) return;
    onSubmit?.(alteration);
  };

  function priceCurrentExceed(params) {
    let result = false;
    if (Number(params?.arCarrierCompanyPrice) > Number(params?.totalPrice)) {
      Notification.open({
        title: '警告⚠️',
        content:
          t`公司费用不可超过任务总价, 任务总价为${alteration?.totalPrice}`,
        type: 'warning',
      });
      result = true;
    }
    return result;
  }

  function currentSendCar(params) {
    const info = params;
    let result = false;
    if (info?.driverInfo && JSON.stringify(info?.driverInfo) !== '{}') {
      const drivers = info?.driverInfo;
      for (let i = 0; drivers < drivers.length; i++) {
        const element = drivers[i];
        if (element?.state !== '0') {
          result = true;
          Notification.open({
            title: '警告⚠️',
            content:
              t`当前任务正在进行, 司机是【${element?.name}】`,
            type: 'warning',
          });
        }
      }
    }
    return result;
  }

  return (
    <Drawer
      visible={visible}
      title={titleElement}
      onClose={onCancel}
      closeMode={['esc', 'mask', 'close']}
      style={{ maxWidth: '80%' }}
      width="90%"
    >
      <Form
        inline
        isPreview={isViewMode}
        {...formProps}
        value={alteration}
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <TitleGrid title={t`任务信息`} />
        <FieldsGrid
          formData={alteration}
          mode={'view'}
          fields={[
            'id', 'crDate',
            'orderBaseModel.subscribeName',
            'orderBaseModel.subscribePhone',
            'orderBaseModel.predictBeginDate',
            'orderBaseModel.predictEndDate',
            'orderBaseModel.portTypeText',
            'orderBaseModel.mileage',
            'orderBaseModel.startMainAreaText',
            'orderBaseModel.startStationName',
            'orderBaseModel.endMainAreaText',
            'orderBaseModel.endStationName',
            'orderBaseModel.beginName',
            'orderBaseModel.endName',
          ]}
        />
        <TitleGrid title={t`承运及费用信息`} />
        <FieldsGrid
          formData={alteration}
          mode={'view'}
          fields={['totalPrice', 'carrierCompanyName', 'departureTime', 'midwayFee']}
        />
        <TitleGrid title={t`变更信息`} />
        <FieldsGrid
          formData={alteration}
          mode={modal[0]}
          overrideModel={overrideModel}
          fields={['arCarrierCompanyId', 'arCarrierCompanyPrice']}
        />
        <DrawerFooter>
          <FromItem>
            {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>
      </Form>
    </Drawer>
  );
};

export default observer(Index);
